package security.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.filter.GenericFilterBean;

import security.core.filter.handler.LogoutProcessHandler;
import security.core.filter.handler.LogoutSuccessHandler;
import security.debug.RBACLogger;

public class LogoutFilter extends GenericFilterBean {
	private String logoutProcessURL;
	private String logoutRedirectURL;
	private LogoutSuccessHandler logoutSuccessHandler;
	private LogoutProcessHandler logoutProcessHandler;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (RBACLogger.debug()) {
			RBACLogger.log("LogoutFilter#doFilter is called!");
		}
		// current URL match the logoutProcessURL, do logout action
		if (isLogoutRequest(request)) {
			// process logout action using logoutProcessHandler
			logoutProcessHandler.logout(request, response);
			// process action after logout using logoutSuccessHandler
			logoutSuccessHandler.onLogoutSuccess(request, response, logoutRedirectURL);
		} else {
			// current URL does not match the logoutProcessURL, go back to the filter chain
			chain.doFilter(request, response);
		}
	}
	
	private Boolean isLogoutRequest(ServletRequest request) {
		if (RBACLogger.debug()) {
			RBACLogger.log("LogoutFilter#isLogoutRequest is called!");
			RBACLogger.log("requesting url is [" + ((HttpServletRequest)request).getRequestURI() + "]");
		}
		return ((HttpServletRequest)request).getRequestURI().equals(logoutProcessURL);
	}

	// setters
	public void setLogoutProcessURL(String logoutProcessURL) {
		if (RBACLogger.debug()) {
			RBACLogger.log("LogoutFilter#setLogoutProcessURL is called!");
		}
		this.logoutProcessURL = logoutProcessURL;
	}

	public void setLogoutRedirectURL(String logoutRedirectURL) {
		this.logoutRedirectURL = logoutRedirectURL;
	}

	public void setLogoutSuccessHandler(LogoutSuccessHandler logoutSuccessHandler) {
		this.logoutSuccessHandler = logoutSuccessHandler;
	}

	public void setLogoutProcessHandler(LogoutProcessHandler logoutProcessHandler) {
		this.logoutProcessHandler = logoutProcessHandler;
	}
}
